package com.android.hidephotosplus;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.android.hidephotosplus.adapter.AlbumAdapter;
import com.android.hidephotosplus.db.DbHelper;
import com.android.hidephotosplus.db.DbProvider;
import com.android.hidephotosplus.interfaces.MInterface.onTask;
import com.android.hidephotosplus.model.ModelAlbum;
import com.android.hidephotosplus.preference.IntPref;
import com.android.hidephotosplus.util.Camera;
import com.android.hidephotosplus.util.Config;
import com.android.hidephotosplus.util.Util;
import com.android.hidephotosplus.util.Util.HiddenMedia;

public class GalleryFragment extends SherlockFragment implements
		OnItemClickListener, OnScrollListener, OnItemLongClickListener {

	public GridView mGridView;

	private AlbumAdapter mAlbumAdapter;

	private ArrayList<ModelAlbum> arrAlbums = new ArrayList<ModelAlbum>();

	private ArrayList<ModelAlbum> arrAlbumsSelected = new ArrayList<ModelAlbum>();

	private Receiver receiver;

	public DbHelper mDbHelper;

	public DbProvider mDbProvider;

	public TextView textEmpty;

	public boolean isStartActionMode = false;

	public ActionMode mActionMode;

	private int position = 0;

	private String navigationSelected = null;

	private boolean isCheckAll = false;

	public ProgressBar progressBar;

	public Camera camera;

	private String[] listNavigation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		mDbHelper = DbHelper.getInstance(getActivity());
		mDbProvider = DbProvider.getinstance(getActivity());
		registerBroadcast();
		position = 0;
		listNavigation = getResources().getStringArray(R.array.listNavigation);
		setupGalleryFragment(listNavigation[IntPref.getPreference(
				getSherlockActivity(), Config.KEY_POSITION_LIST_NAVIGATION, 0)]);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.gallery_fragment, null);
		textEmpty = (TextView) view.findViewById(R.id.textEmpty);
		textEmpty.setText(getString(R.string.empty_album));
		progressBar = (ProgressBar) view.findViewById(R.id.progressEmpty);
		mGridView = (GridView) view.findViewById(R.id.gridAlbum);
		mGridView.setEmptyView(progressBar);
		mGridView.setOnItemClickListener(this);
		mGridView.setOnItemLongClickListener(this);
		mGridView.setOnScrollListener(this);

		mAlbumAdapter = new AlbumAdapter(getActivity(), arrAlbums, true);
		mGridView.setAdapter(mAlbumAdapter);
		mGridView.setEmptyView(textEmpty);
		return view;
	}

	public void setupGalleryFragment(String type_media) {
		if (type_media.equals(getActivity().getString(R.string.all_media))) {
			navigationSelected = getString(R.string.all_media);
			arrAlbums.clear();
			arrAlbums.addAll(mDbProvider.getAllAlbum());
		} else if (type_media.equals(getActivity().getString(R.string.photos))) {
			navigationSelected = getString(R.string.photos);
			arrAlbums.clear();
			arrAlbums.addAll(mDbProvider.getAllAlbumPhotos(false));
		} else {
			navigationSelected = getString(R.string.videos);
			arrAlbums.clear();
			arrAlbums.addAll(mDbProvider.getAllAlbumVideos(false, null));
		}
		if (mAlbumAdapter != null) {
			mAlbumAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (!isStartActionMode) {
			this.position = position;
			Intent intent = new Intent(getActivity(), ActivityAlbumView.class);
			intent.putExtra(Config.KEY_ALBUM_STOCK,
					mAlbumAdapter.getItem(position));
			intent.putExtra(Config.KEY_NAVIGATION_SELECTED, navigationSelected);
			startActivityForResult(intent, Config.REQUEST_CODE_ALBUMVIEW_STOCK);
		} else {
			setSelectedUnSelected(position, arrAlbums, arrAlbumsSelected,
					mAlbumAdapter, mActionMode);
		}

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long arg3) {
		if (!isStartActionMode) {
			mActionMode = getSherlockActivity().startActionMode(
					new AnActionMode(true));
		}
		setSelectedUnSelected(position, arrAlbums, arrAlbumsSelected,
				mAlbumAdapter, mActionMode);
		return true;
	}

	private void registerBroadcast() {
		try {
			IntentFilter filter = new IntentFilter();
			filter.addAction(Config.ACTION_SEND_TYPE_MEDIA);
			filter.addAction(Config.ACTION_SEND_ARR_ALBUM_HIDDEN_TO_STOCK);
			filter.addAction(Config.ACTION_SEND_NAME_ALBUM_TO_STOCK);
			receiver = new Receiver();
			getActivity().registerReceiver(receiver, filter);
		} catch (Exception e) {
			Log.e("ExceptionException", "registerBroadcast");
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			getActivity().unregisterReceiver(receiver);
		} catch (Exception e) {
		}
	}

	private class Receiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					Config.ACTION_SEND_ARR_ALBUM_HIDDEN_TO_STOCK)) {
				if (intent.getExtras() != null) {
					ArrayList<ModelAlbum> arrAlbumsHidden = intent
							.getParcelableArrayListExtra(Config.KEY_ARR_ALBUM_HIDDEN);
					for (ModelAlbum album : arrAlbumsHidden) {
						boolean isExists = false;
						for (ModelAlbum albumStock : arrAlbums) {
							if (album.getNameAlbum().equals(
									albumStock.getNameAlbum())) {
								isExists = true;
								setMediaOfAlbum(albumStock);
							}
						}
						if (!isExists) {
							ArrayList<ModelAlbum> arrAlbumsStock = getNewAlbum(album);
							arrAlbums.addAll(arrAlbumsStock);
						}
					}
					if (mAlbumAdapter != null)
						mAlbumAdapter.notifyDataSetChanged();
				}
			} else if (intent.getAction().equals(
					Config.ACTION_SEND_NAME_ALBUM_TO_STOCK)) {
				if (intent.getExtras() != null) {
					String nameAlbum = intent.getExtras().getString(
							Config.KEY_NAME_ALBUM_STOCK);
					boolean isExists = false;
					for (ModelAlbum albumStock : arrAlbums) {
						if (nameAlbum.equals(albumStock.getNameAlbum())) {
							isExists = true;
							setMediaOfAlbum(albumStock);
						}
					}
					if (!isExists) {
						ArrayList<ModelAlbum> arrAlbumsStock = getNewAlbumByName(nameAlbum);
						arrAlbums.addAll(arrAlbumsStock);
					}
					if (mAlbumAdapter != null)
						mAlbumAdapter.notifyDataSetChanged();
				}
			}
		}

	}

	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (view.getId() == R.id.gridAlbum) {
			if (scrollState == SCROLL_STATE_FLING) {
				mAlbumAdapter.setScroolState(true);
			} else {
				mAlbumAdapter.setScroolState(false);
				mAlbumAdapter.notifyDataSetChanged();
			}
		}
	}

	public class AnActionMode implements ActionMode.Callback {
		private boolean isPublic;

		public AnActionMode(boolean isPublic) {
			this.isPublic = isPublic;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			MenuInflater inflater = mode.getMenuInflater();
			if (isPublic)
				inflater.inflate(R.menu.actionmode_album_view_stock, menu);
			else
				inflater.inflate(R.menu.actionmode_album_view_hidden, menu);
			isStartActionMode = true;
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {

			case R.id.menu_check_all:
				if (!isCheckAll) {
					setCheckUncheckAll(true, arrAlbums, arrAlbumsSelected,
							mActionMode, mAlbumAdapter);
					isCheckAll = true;
				} else {
					setCheckUncheckAll(false, arrAlbums, arrAlbumsSelected,
							mActionMode, mAlbumAdapter);
					isCheckAll = false;
				}
				break;
			case R.id.menu_hide:
				new HiddenMedia(getActivity(), null, arrAlbumsSelected,
						navigationSelected, true, new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								sendBroadcastAlbumStock(arrAlbumsSelected);
								arrAlbums.removeAll(arrAlbumsSelected);
								mAlbumAdapter.notifyDataSetChanged();
								mActionMode.finish();
							}
						}).execute();
				break;
			case R.id.menu_delete:
				new Util.DeleteMediaStock(getActivity(), null,
						arrAlbumsSelected, navigationSelected, true,
						new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								sendBroadcastAlbumStock(arrAlbumsSelected);
								arrAlbums.removeAll(arrAlbumsSelected);
								mAlbumAdapter.notifyDataSetChanged();
								mActionMode.finish();
							}
						}).execute();
				break;
			case R.id.menu_share:
				new Util.ShareFileStock(getSherlockActivity(), arrAlbums, null,
						navigationSelected).execute();
				break;
			default:
				break;
			}

			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			isStartActionMode = false;
			setCheckUncheckAll(false, arrAlbums, arrAlbumsSelected,
					mActionMode, mAlbumAdapter);
			arrAlbumsSelected.clear();
		}

	}

	public void setSelectedUnSelected(int position,
			ArrayList<ModelAlbum> arrAlbums,
			ArrayList<ModelAlbum> arrAlbumsSelected,
			AlbumAdapter mAlbumAdapter, ActionMode mActionMode) {
		arrAlbums.get(position).isChecked = !arrAlbums.get(position).isChecked;
		mAlbumAdapter.notifyDataSetChanged();
		if (arrAlbums.get(position).isChecked)
			arrAlbumsSelected.add(arrAlbums.get(position));
		else
			arrAlbumsSelected.remove(arrAlbums.get(position));
		mActionMode.setTitle(arrAlbumsSelected.size() + " "
				+ getString(R.string.selected));
		mAlbumAdapter.notifyDataSetChanged();
	}

	public void setCheckUncheckAll(boolean isChecked,
			ArrayList<ModelAlbum> arrAlbums,
			ArrayList<ModelAlbum> arrAlbumsSelected, ActionMode mActionMode,
			AlbumAdapter mAlbumAdapter) {
		if (arrAlbumsSelected.size() > 0)
			arrAlbumsSelected.clear();
		for (ModelAlbum item : arrAlbums) {
			if (isChecked) {
				item.setChecked(true);
				arrAlbumsSelected.add(item);
			} else {
				arrAlbumsSelected.clear();
				item.setChecked(false);
			}
		}
		mActionMode.setTitle(arrAlbumsSelected.size() + " "
				+ getString(R.string.selected));
		mAlbumAdapter.notifyDataSetChanged();
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		if (isStartActionMode)
			mActionMode.finish();
	}

	public void sendBroadcastAlbumStock(ArrayList<ModelAlbum> arrAlbums) {
		Intent intent = new Intent();
		intent.setAction(Config.ACTION_SEND_ARR_ALBUM_STOCK_TO_HIDDEN);
		intent.putExtra(Config.KEY_ARR_ALBUM_STOCK, arrAlbums);
		getActivity().sendBroadcast(intent);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case Config.REQUEST_CODE_ALBUMVIEW_STOCK:
			FragmentMain.IS_START_PASSWORD = false;
			if (position >= 0 && position < arrAlbums.size()) {
				if (getActivity().getString(R.string.all_media).equals(
						navigationSelected)) {
					arrAlbums.get(position).setMediaOfAlbum(
							mDbProvider.getMediaOfAlbum(arrAlbums.get(position)
									.getIdAlbum()));
					arrAlbums.get(position).setNumberMedia(
							mDbProvider.numberPhoto(arrAlbums.get(position)
									.getIdAlbum())
									+ mDbProvider.numberVideo(arrAlbums.get(
											position).getIdAlbum()));
				} else if (getActivity().getString(R.string.photos).equals(
						navigationSelected)) {
					arrAlbums.get(position).setMediaOfAlbum(
							mDbProvider.getMediaOfAlbumPhoto(arrAlbums.get(
									position).getIdAlbum()));
					arrAlbums.get(position).setNumberMedia(
							mDbProvider.numberPhoto(arrAlbums.get(position)
									.getIdAlbum()));
				} else {
					arrAlbums.get(position).setMediaOfAlbum(
							mDbProvider.getMediaOfAlbumVideo(arrAlbums.get(
									position).getIdAlbum()));
					arrAlbums.get(position).setNumberMedia(
							mDbProvider.numberVideo(arrAlbums.get(position)
									.getIdAlbum()));
				}

				mAlbumAdapter.notifyDataSetChanged();
			}
			break;
		case Config.REQUEST_CODE_SHARE_FILE:
			FragmentMain.IS_START_PASSWORD = false;
			mActionMode.finish();
			break;
		default:
			break;
		}
	}

	// Receiver
	private void setMediaOfAlbum(ModelAlbum albumStock) {
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			albumStock.setMediaOfAlbum(mDbProvider.getMediaOfAlbum(albumStock
					.getIdAlbum()));
			albumStock.setNumberMedia(mDbProvider.numberPhoto(albumStock
					.getIdAlbum())
					+ mDbProvider.numberVideo(albumStock.getIdAlbum()));
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			albumStock.setMediaOfAlbum(mDbProvider
					.getMediaOfAlbumPhoto(albumStock.getIdAlbum()));
			albumStock.setNumberMedia(mDbProvider.numberPhoto(albumStock
					.getIdAlbum()));
		} else {
			Log.e("-----", "++++++");
			albumStock.setMediaOfAlbum(mDbProvider
					.getMediaOfAlbumVideo(albumStock.getIdAlbum()));
			albumStock.setNumberMedia(mDbProvider.numberVideo(albumStock
					.getIdAlbum()));
		}

	}

	private ArrayList<ModelAlbum> getNewAlbum(ModelAlbum album) {
		ArrayList<ModelAlbum> arrAlbumsStock = new ArrayList<ModelAlbum>();
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			arrAlbumsStock = mDbProvider.getAllAlbumByNameAlbum(album
					.getNameAlbum());
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			arrAlbumsStock = mDbProvider.getAllAlbumPhotosByNameAlbum(false,
					album.getNameAlbum());
		} else {
			arrAlbumsStock = mDbProvider.getAllAlbumVideosByNameAlbum(false,
					album.getNameAlbum(), null);
		}
		return arrAlbumsStock;
	}

	private ArrayList<ModelAlbum> getNewAlbumByName(String nameAlbum) {
		ArrayList<ModelAlbum> arrAlbumsStock = new ArrayList<ModelAlbum>();
		if (getActivity().getString(R.string.all_media).equals(
				navigationSelected)) {
			arrAlbumsStock = mDbProvider.getAllAlbumByNameAlbum(nameAlbum);
		} else if (getActivity().getString(R.string.photos).equals(
				navigationSelected)) {
			arrAlbumsStock = mDbProvider.getAllAlbumPhotosByNameAlbum(false,
					nameAlbum);
		} else {
			arrAlbumsStock = mDbProvider.getAllAlbumVideosByNameAlbum(false,
					nameAlbum, null);
		}
		return arrAlbumsStock;
	}

}
